import { Rule } from 'ant-design-vue/es/form'

import { countStrToBit } from './index'

export const regex = {
  basicName: /^[\u4e00-\u9fa5a-zA-Z0-9-_（）().]+$/, // 仅支持中英文、数字、横线、下划线、括号、小数点
  attrName: /^[\u4e00-\u9fa5a-zA-Z0-9]+$/,
  version: /^(?!\.)(\d+\.)*\d+$/,
  // 仅支持中英文
  username: /^[\u4e00-\u9fa5a-zA-Z]+$/,
  // 仅支持中英文数字
  CHENNumber: /^[\u4e00-\u9fa5a-zA-Z0-9]+$/,
  phone: /^1[3456789]\d{9}$/,
  password:
    /^(?:(?=.*[a-z])(?=.*[A-Z])(?=.*\d)|(?=.*[a-z])(?=.*[A-Z])(?=.*[\W_])|(?=.*[a-z])(?=.*\d)(?=.*[\W_])|(?=.*[A-Z])(?=.*\d)(?=.*[\W_]))[^\u4e00-\u9fa5\u3040-\u30FF\uAC00-\uD7AF]+$/,
  dirName: /^[^\\\\/:*?"<>|]*$/
}

/**
 * 接受两个参数 生成满足两个参数范围内的字符长度正则
 */
export const createLengthReg = (min: number, max: number) => {
  return new RegExp(`^[\\s\\S]{${min},${max}}$`)
}

/**
 * 密码校验
 */
export const passwordValidator = (_rule: Rule, value: string, userName?: string) => {
  if (!value.trim()) {
    return Promise.reject('请输入密码')
  }
  if (!createLengthReg(8, 15).test(value)) {
    return Promise.reject('密码的长度为8-15位')
  }
  if (!regex.password.test(value)) {
    return Promise.reject('密码至少包含大、小写字母、数字和特殊字符中的三项')
  }
  if (value === userName) {
    return Promise.reject('不可与账号名重复')
  }
  return Promise.resolve()
}
// 校验字节长度
export const validateBitLen = (maxLen = 200, name = '名称') => {
  return async (_rule: Rule, value: string) => {
    if (countStrToBit(value) > maxLen) {
      return Promise.reject(`${name}不可超过${maxLen}字节`)
    } else {
      return Promise.resolve()
    }
  }
}
// 校验文件夹名称或其他基础名称
export const validateDirName = (name = '名称') => {
  return async (_rule: Rule, value: string) => {
    if (!regex.dirName.test(value)) {
      return Promise.reject(`${name}不能包含\\ / : * ? " < > |`)
    } else {
      return Promise.resolve()
    }
  }
}
